package com.etu.common.imagetools;

/**
 *@author Administrator
 *@date Jan 17, 2010
 */
import javax.imageio.ImageIO;


import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.io.File;

/**
 * 生成缩略图的工具类
 * @author xinyu126
 * @version 1.0
 */
public class ThumbImgCreator {
	
	
	/**
	 * @param fromFile
	 * @param width
	 * @param hight
	 * @return
	 * @throws Exception
	 * 
	 * boolean
	 */
	public static boolean createThumb(File fromFile,
			int width, int hight) throws Exception {
		File saveFile=new File(fromFile.getPath(),"min_"+fromFile.getName());
		return createThumb(fromFile,saveFile,width,hight,true);
	}
	
	/**
	 * @param fromFile 
	 * @param saveFile 
	 * @param width
	 * @param hight
	 * @return boolean
	 * @throws Exception
	 * @see <code>createThumb(File fromFile, File saveFile,int width, int hight,boolean keepRatio)</code>
	 * 
	 **/
	public static boolean createThumb(File fromFile, File saveFile,
			int width, int hight) throws Exception {
		return createThumb(fromFile,saveFile,width,hight,true);
	}
	
	/**
	 * @param fromFile 源文件
	 * @param saveFile 要生成的缩略图
	 * @param width 宽度
	 * @param hight 高度
	 * @param keepRatio 是否保持横宽比例 default:true
 	 * @return boolean 生成成功返回true
	 * @throws Exception
	 * 
	 * 
	 */
	public static boolean createThumb(File fromFile, File saveFile,
			int width, int hight,boolean keepRatio) throws Exception {
		BufferedImage srcImage;
		String imgType = "JPEG";
		srcImage = ImageIO.read(fromFile);
		if (width > 0 || hight > 0) {
			srcImage = resize(srcImage, width, hight,keepRatio);
		}
		return ImageIO.write(srcImage, imgType, saveFile);
	}
	


	private static BufferedImage resize(BufferedImage source, int targetW,
			int targetH,boolean keepRatio) {
		// targetW，targetH分别表示目标长和宽
		int type = source.getType();
		BufferedImage target = null;
		
		float sx = (float) targetW / source.getWidth();
		float sy = (float) targetH / source.getHeight();
		
		if(keepRatio){
			if(sx>sy){
				sx=sy;
				targetW=(int)(source.getWidth()*sx);
			}else{				
				sy=sx;
				targetH=(int)(source.getHeight()*sy);
			}
		}
		
		if (type == BufferedImage.TYPE_CUSTOM) {
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
					targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else{
			target = new BufferedImage(targetW, targetH, type);
		}
		Graphics2D g = target.createGraphics();
		
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}
}
